{% extends "base.html" %}
{% load i18n %}
{% load static %}
{% block content %}
    <div id="content">

    <!-- Begin Page Content -->
    <div class="container-fluid">

        <!-- Page Heading -->
        <h1 class="h3 mb-2 text-gray-800">任务列表</h1>

        <!-- 审批通过模态框 -->
        <div class="modal fade" id="approveConfirmModal" tabindex="-1" role="dialog" aria-labelledby="approveConfirmModal" aria-hidden="true">
          <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
              <!-- 模态框头部 -->
              <div class="modal-header">
                <h5 class="modal-title" id="approveConfirmModalLabel">确认操作</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <!-- 模态框主体内容 -->
              <div class="modal-body">
                您确定审批通过ID = <span id="task_msg" class="text-danger"></span>的任务么? 请注意: <br><br>
                  1. 立即执行任务在审批通过后1分钟内执行;<br><br>
                  2. 定时执行任务按照Cron内容执行
              </div>
              <div class="modal-body">
                <label class="mr-3 w-100"><span id="approve_confirm_msg" class="text-danger"></span></label>
              </div>
              <!-- 模态框底部 -->
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="approveConfirmButton" onclick="approve_task()">确认</button>
              </div>
            </div>
          </div>
        </div>

        <!-- 撤回模态框 -->
        <div class="modal fade" id="withdrawConfirmModal" tabindex="-1" role="dialog" aria-labelledby="withdrawConfirmModal" aria-hidden="true">
          <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
              <!-- 模态框头部 -->
              <div class="modal-header">
                <h5 class="modal-title" id="withdrawConfirmModalLabel">确认操作</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <!-- 模态框主体内容 -->
              <div class="modal-body">
                您确定撤回ID = <span id="task_id" class="text-danger"></span>的任务么? 请注意: <br><br>
                  1. 撤回任务不可重新编辑<br><br>
                  2. 撤回任务内容需重新填写后再提交
              </div>
              <div class="modal-body">
                <label class="mr-3 w-100"><span id="withdraw_confirm_msg" class="text-danger"></span></label>
              </div>
              <!-- 模态框底部 -->
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="withdrawConfirmButton" onclick="withdraw_task()">确认</button>
              </div>
            </div>
          </div>
        </div>

        <!-- 终止模态框 -->
        <div class="modal fade" id="stopConfirmModal" tabindex="-1" role="dialog" aria-labelledby="withdrawConfirmModal" aria-hidden="true">
          <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
              <!-- 模态框头部 -->
              <div class="modal-header">
                <h5 class="modal-title" id="stopConfirmModalLabel">确认操作</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <!-- 模态框主体内容 -->
              <div class="modal-body">
                您确定终止ID = <span id="stop_task_id" class="text-danger"></span>的任务么? 请注意: <br><br>
                  1. 被终止任务不可重新编辑<br><br>
                  2. 被终止的"待执行"状态任务不会继续执行, 立即退出<br><br>
                  3. 被终止的"执行中"状态任务会执行完本次，不会继续执行之后剩余任务
              </div>
              <div class="modal-body">
                <label class="mr-3 w-100"><span id="stop_confirm_msg" class="text-danger"></span></label>
              </div>
              <!-- 模态框底部 -->
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="stopConfirmButton" onclick="stop_task()">确认</button>
              </div>
            </div>
          </div>
        </div>

        <!-- 审批拒绝模态框 -->
        <div class="modal fade" id="rejectConfirmModal" tabindex="-1" role="dialog" aria-labelledby="rejectConfirmModal" aria-hidden="true">
          <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
              <!-- 模态框头部 -->
              <div class="modal-header">
                <h5 class="modal-title" id="rejectConfirmModalLabel">确认操作</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <!-- 模态框主体内容 -->
              <div class="modal-body">
                您确定拒绝通过ID = <span id="reject_task_msg" class="text-danger"></span>的任务么? 如果确认，请描述清楚拒绝原因: <br><br>
                  <textarea id="reject_reason" class="form-control" placeholder="请输入拒绝原因" rows="5" style="resize: vertical; width: 100%;"></textarea>
              </div>
              <div class="modal-body">
                <label class="mr-3 w-100"><span id="reject_confirm_msg" class="text-danger"></span></label>
              </div>
              <!-- 模态框底部 -->
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="rejectConfirmButton" onclick="reject_task()">确认</button>
              </div>
            </div>
          </div>
        </div>

        <!-- 详情模态框 -->
        <div class="modal fade" id="detailModal" tabindex="-1" role="dialog" aria-labelledby="detailModalLabel" aria-hidden="true">
          <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="detailModalLabel">任务执行详情</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-body">
                <table class="table table-bordered">
                  <thead>
                    <tr>
                      <th>选项</th>
                      <th>内容</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr id="tr-approver" style="display: none">
                      <td>审批人</td>
                      <td id="approver"></td>
                    </tr>
                    <tr>
                      <td>审批结果</td>
                      <td id="approve_result"></td>
                    </tr>
                    <tr>
                      <td>执行命令</td>
                      <td id="execute_shell"></td>
                    </tr>
                    <tr>
                      <td>任务结果</td>
                      <td id="execute_result">
                          <label class="mr-3 w-100">执行成功: <span id="count_success" class="text-danger"></span></label>
                          <label class="mr-3 w-100">执行失败: <span id="count_fail" class="text-danger"></span></label>
                          <label class="mr-3 w-100">执行结果详见: <a id="detail_file" href="#" onclick="download_execute_result()"></a></label>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
              </div>
            </div>
          </div>
        </div>


        <!-- DataTales Example -->
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <span class="text-danger">    </span>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                        <thead>
                            <tr>
                                <th>Task ID</th>
                                <th>任务名称</th>
                                <th>操作主机组</th>
                                <th>执行策略</th>
                                <th>执行次数</th>
                                <th>任务状态</th>
                                <th>创建用户</th>
                                <th>审批人</th>
                                <th>创建时间</th>
                                <th>更新时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tfoot>
                            <tr>
                                <th>Task ID</th>
                                <th>任务名称</th>
                                <th>操作主机组</th>
                                <th>执行策略</th>
                                <th>执行次数</th>
                                <th>任务状态</th>
                                <th>创建用户</th>
                                <th>审批人</th>
                                <th>创建时间</th>
                                <th>更新时间</th>
                                <th>操作</th>
                            </tr>
                        </tfoot>

                    </table>
                </div>
            </div>
        </div>

    </div>
    <!-- /.container-fluid -->
    <div id="load" class="position-fixed w-100 h-100"
     style="top: 0; left: 0; background: rgba(255, 255, 255, 0.2); z-index: 1100; display: none;
            justify-content: center;
            align-items: center;">
        <div class="spinner-border text-success" role="status" style="width: 3rem; height: 3rem; position: absolute; top: 50%; left: 50%; margin-top: -1.5rem; margin-left: -1.5rem;">
        <span class="sr-only">加载中...</span>
    </div>
{% endblock content %}
{% block js %}
    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function () {
            // 检查 DataTable 是否已经初始化
            if ($.fn.DataTable.isDataTable('#dataTable')) {
                $('#dataTable').DataTable().destroy(); // 销毁已有实例
            }

            // 定义 DataTable 的基础列
            var columns = [
                { "data": "id" },
                { "data": "name" },
                { "data": "host_group_name__name" },
                {
                    "data": "execute_policy",
                    "render": function(data, type, row) {
                        if (data == "1") {
                            return "立即执行";
                        } else {
                            return "定时执行: " + data;
                        }
                    }
                },
                { "data": "repeat_num" },
                {
                    "data": "status",
                    "render": function(data, type, row) {
                        var statusClass = "";
                        var statusText = row.status_display;

                        switch(data) {
                            case 2:
                                statusClass = "text-success";
                                break;
                            case 3:
                                statusClass = "text-primary";
                                break;
                            case 0:
                                statusClass = "text-warning";
                                break;
                            case 1:
                                statusClass = "text-danger";
                                break;
                        }

                        return `<span class="${statusClass}">${statusText}</span>`;
                    }
                },
                { "data": "user__username" },
                { "data": "approver__username" },
                { "data": "create_time" },
                { "data": "update_time" }
            ];

            // 从Django模板获取用户权限信息
            var is_superuser = {{ request.user.is_superuser|yesno:"true,false" }};

            // 添加操作按钮列
            columns.push({
                "data": "id",
                "orderable": false,
                "searchable": false,
                "render": function(data, type, row) {
                    var buttons = '';

                    if (is_superuser) {
                        // 超级用户可以看到同意/拒绝按钮
                        buttons += `
                            <button type="button"
                                style="${row.status != 0 ? 'display: none;' : ''}"
                                class="btn btn-warning btn-sm"
                                onclick="accept_taskid(this)"
                                id="${row.id}">同意</button>
                            <button type="button"
                                style="${row.status != 0 ? 'display: none;' : ''}"
                                class="btn btn-danger btn-sm"
                                onclick="reject_taskid(this)"
                                id="r-${row.id}">拒绝</button>
                        `;
                    } else {
                        // 普通用户可以看到撤回按钮
                        buttons += `
                            <button type="button"
                                style="${row.status != 0 ? 'display: none;' : ''}"
                                class="btn btn-warning btn-sm"
                                onclick="withdraw_taskid(this)"
                                value="${row.id}">撤回</button>
                        `;
                    }

                    // 所有用户都可以看到终止和详情按钮
                    buttons += `
                        <button type="button"
                            style="${(row.status != 1 && row.status != 3) ? 'display: none;' : ''}"
                            class="btn btn-danger btn-sm"
                            onclick="stop_taskid(this)"
                            value="${row.id}">终止</button>
                        <button type="button"
                            class="btn btn-info btn-sm"
                            onclick="get_task_info(this)"
                            value="${row.id}">详情</button>
                    `;

                    return buttons;
                }
            });

            // 初始化 DataTable
            $('#dataTable').DataTable({
                "pageLength": 25,
                "processing": true,
                "serverSide": true,
                "ajax": "/get_tasks/",
                "columns": columns,
                "order": [[ 0, "desc" ]], // 按ID降序排列
            });
        });

        // 设置加载图片
        function loading() {
            document.getElementById('load').style.display = 'flex';
        };

        // 移除加载图片
        function loading_remove() {
            document.getElementById('load').style.display = 'none';
        };

        // 移除reminder
        function reminder_remove() {
            var approve_confirm_msg = document.getElementById("approve_confirm_msg");
            approve_confirm_msg.innerHTML = '';
        };

        // 弹出刷新确认框
        function refresh_confirm() {
            var refresh_confirm_msg = document.getElementById("refresh_confirm_msg");
            refresh_confirm_msg.innerHTML = '';
            $('#refreshConfirmModal').modal('show');
        };

        //下载文件
        function download_execute_result() {
            $.ajax({
                type: "post",
                url: "/download_execute_result/",
                data: {
                    filename: document.querySelector('#detail_file').getAttribute('data-value'),
                },
                xhrFields: {
                    responseType: 'blob'
                },
                 success: function(blob, status, xhr) {
                    // 从响应头中获取后端设置的文件名
                    const filename = xhr.getResponseHeader('Content-Disposition')
                        ?.split('filename=')[1]
                        ?.replace(/"/g, '') || 'downloaded_file.txt';

                    // 创建 Blob 对象的 URL
                    const url = window.URL.createObjectURL(blob);

                    // 动态创建 <a> 元素进行下载
                    const link = document.createElement('a');
                    link.href = url;
                    link.download = filename;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    window.URL.revokeObjectURL(url);
                },
                error: function(xhr, status, error) {
                    console.log('error:', error);
                }
            });
        }

        // 点击详情按钮时显示任务信息
        function get_task_info(button) {
            $.ajax({
                type: "post",
                url: "/get_task_info/",
                dataType: "json",
                data: {
                    task_id: button.value,
                },
                complete: function () {
                },
                success: function (data) {
                    if (data.status === 0) {
                        document.getElementById("tr-approver").style.display = 'none';
                        if (data.approve_status === 0) {
                            document.getElementById("tr-approver").style.display = '';
                            document.getElementById("approver").innerText = data.superuser_list;
                        }
                        document.getElementById("approve_result").innerText = data.approve_result;
                        document.getElementById("execute_shell").innerText = data.shell;
                        document.getElementById("count_success").innerText = data.msg.count_success;
                        document.getElementById("count_fail").innerText = data.msg.count_fail;
                        document.getElementById("detail_file").innerText = data.msg.exec_remote_shell_result_filename;
                        var detail_file = document.getElementById("detail_file");
                        $('#detail_file').attr('data-value', data.msg.exec_remote_shell_result_filename);
                    } else {
                        document.getElementById("count_success").innerText = "";
                        document.getElementById("count_fail").innerText = "";
                        document.getElementById("detail_file").innerText = "";
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                }
            });

            // 显示确认框
            $('#detailModal').modal('show');
        }

        // 点击同意按钮时设置确认按钮
        function accept_taskid(button) {
            // 设置确认按钮的 data-id 属性
            document.querySelector('#approveConfirmButton').setAttribute('data-id', button.id);
            document.getElementById("task_msg").innerHTML = button.id;

            // 显示确认框
            reminder_remove();
            $('#approveConfirmModal').modal('show');
        }

        // 审批同意任务
        function approve_task() {
            loading();
            var approve_confirm_msg = document.getElementById("approve_confirm_msg");
            $.ajax({
                type: "post",
                url: "/approve_task/",
                dataType: "json",
                data: {
                    task_id: document.querySelector('#approveConfirmButton').getAttribute('data-id'),
                },
                complete: function () {
                },
                success: function (data) {
                    loading_remove();
                    if (data.status === 0) {
                        approve_confirm_msg.innerHTML = 'Reminder: ' + data.msg;
                        location.reload();
                    } else {
                        approve_confirm_msg.innerHTML = 'Reminder: ' + data.msg;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    loading_remove();
                    approve_confirm_msg.innerHTML = 'Reminder: ' + errorThrown;
                }
            });
        }

        // 点击撤回按钮时设置确认按钮
        function withdraw_taskid(button) {
            // 设置确认按钮的 data-id 属性
            document.querySelector('#withdrawConfirmButton').setAttribute('data-id', button.value);
            document.getElementById("task_id").innerHTML = button.value;

            // 显示确认框
            reminder_remove();
            $('#withdrawConfirmModal').modal('show');
        }

        // 撤回任务
        function withdraw_task() {
            loading();
            var withdraw_confirm_msg = document.getElementById("withdraw_confirm_msg");
            $.ajax({
                type: "post",
                url: "/withdraw_task/",
                dataType: "json",
                data: {
                    task_id: document.querySelector('#withdrawConfirmButton').getAttribute('data-id'),
                },
                complete: function () {
                },
                success: function (data) {
                    loading_remove();
                    if (data.status === 0) {
                        withdraw_confirm_msg.innerHTML = 'Reminder: ' + data.msg;
                        location.reload();
                    } else {
                        withdraw_confirm_msg.innerHTML = 'Reminder: ' + data.msg;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    loading_remove();
                    approve_confirm_msg.innerHTML = 'Reminder: ' + errorThrown;
                }
            });
        }

        // 点击终止按钮时设置确认按钮
        function stop_taskid(button) {
            // 设置确认按钮的 data-id 属性
            document.querySelector('#stopConfirmButton').setAttribute('data-id', button.value);
            document.getElementById("stop_task_id").innerHTML = button.value;

            // 显示确认框
            reminder_remove();
            $('#stopConfirmModal').modal('show');
        }

        // 终止任务
        function stop_task() {
            loading();
            var stop_confirm_msg = document.getElementById("stop_confirm_msg");
            $.ajax({
                type: "post",
                url: "/stop_task/",
                dataType: "json",
                data: {
                    task_id: document.querySelector('#stopConfirmButton').getAttribute('data-id'),
                },
                complete: function () {
                },
                success: function (data) {
                    loading_remove();
                    if (data.status === 0) {
                        stop_confirm_msg.innerHTML = 'Reminder: ' + data.msg;
                        location.reload();
                    } else {
                        stop_confirm_msg.innerHTML = 'Reminder: ' + data.msg;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    loading_remove();
                    approve_confirm_msg.innerHTML = 'Reminder: ' + errorThrown;
                }
            });
        }

        // 点击拒绝按钮时设置确认按钮
        function reject_taskid(button) {
            // 设置确认按钮的 data-id 属性
            document.querySelector('#rejectConfirmButton').setAttribute('data-id', button.id);
            document.getElementById("reject_task_msg").innerHTML = button.id.slice(2);

            // 显示确认框
            reminder_remove();
            $('#rejectConfirmModal').modal('show');
        }

        // 审批拒绝任务
        function reject_task() {
            loading();
            var reject_confirm_msg = document.getElementById("reject_confirm_msg");
            $.ajax({
                type: "post",
                url: "/reject_task/",
                dataType: "json",
                data: {
                    task_id: document.querySelector('#rejectConfirmButton').getAttribute('data-id'),
                    reject_reason: document.getElementById("reject_reason").value,
                },
                complete: function () {
                },
                success: function (data) {
                    loading_remove();
                    if (data.status === 0) {
                        reject_confirm_msg.innerHTML = 'Reminder: ' + data.msg;
                        location.reload();
                    } else {
                        reject_confirm_msg.innerHTML = 'Reminder: ' + data.msg;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    loading_remove();
                    approve_confirm_msg.innerHTML = 'Reminder: ' + errorThrown;
                }
            });
        }
    </script>
{% endblock %}